'''
Created on Aug 10, 2011

@author: mark
'''
import Tkinter as tk
from dialog.BlockEditorDialog import BlockEditorDlg
from dialog.tkSimpleDialog import InputDialog
import tkFileDialog
from data.game import load_game, Game
import tkMessageBox
from solve.Process import solve as process_solve

class BoardEditor(object):
    '''
    classdocs
    '''

    def add_bench(self):
        for widget in self.benchWidgets:
            widget.grid_remove()
        self.benchWidgets = []
        col_num = 0
        for tile in self.game.bench:
            entry = tk.Label(self.benchFrame, width=3, justify=tk.CENTER, relief=tk.SUNKEN)
            entry.grid(row=0, column=col_num)
            entry.configure(background='#FFC', foreground='#00F', text=tile)
            self.benchWidgets.append(entry)
            col_num += 1
        

    def __init__(self, board, game):
        '''
        Constructor
        '''
        self.game = game
        self.root = tk.Tk()
        self.root.title("Words With Friends Solver")
        self.benchWidgets=[]
        self.board = board
        row_num = 0
        self.entries = []
        for row in self.board:
            self.entries.append([])
            col_num=0
            for col_num in xrange(len(row)):
                entry = tk.Label(self.root, width=3, justify=tk.CENTER, relief=tk.SUNKEN, bd=2)
                entry.grid(row=row_num, column=col_num)
                entry.col = col_num
                entry.row = row_num
                entry.bind('<Button-1>', self.change_value)
                entry.bind('<Shift-Button-1>', self.clear_value)
                entry.bind('<Control-Button-1>', self.insert_down)
                entry.bind('<Control-Button-3>', self.insert_right)
                self.entries[row_num].append(entry)  
                self.format_entry(row_num, col_num)
            row_num += 1
        
        self.benchFrame = tk.LabelFrame(self.root, text="Bench")
        self.benchFrame.grid(row=row_num, columnspan=len(self.board))
        row_num += 1
        resetBtn = tk.Button(self.benchFrame, text='Set', command=self.reset_bench)
        self.add_bench()
        resetBtn.grid(row=1, columnspan=7)
        
        self.controlFrame = tk.LabelFrame(self.root, text='Controls')
        self.controlFrame.grid(row=row_num, columnspan=len(self.board))
        tk.Button(self.controlFrame, text="Save...", command=self.saveGame).grid(row=0, column=0, padx=5, pady=5)
        tk.Button(self.controlFrame, text="Load...", command=self.load_game).grid(row=0, column=1, padx=5, pady=5)
        tk.Button(self.controlFrame, text="Clear...", command=self.clear_board).grid(row=0, column=2, padx=5, pady=5)
        tk.Button(self.controlFrame, text="Solve...", command=self.solve).grid(row=0, column=3, padx=5, pady=5)
        
        self.root.mainloop()
        
    def reset_bench(self, event=None):
        d = InputDialog(self.root, 'Enter the new bench string. Max 7 letters.', 'Reset Bench')
        if not d.canceled:
            benchStr = d.input
            for letter in xrange(len(self.game.bench)):
                self.game.bench.pop()
                self.benchWidgets.pop().grid_forget()
            for letter in benchStr[0: min(7, len(d.input))]:
                self.game.bench.append(letter)
            self.add_bench()
       
    def change_value(self, event=None):
        if event and event.widget:
            row = event.widget.row
            col = event.widget.col
            d = BlockEditorDlg(self.root, row, col, self.game.user[row][col])
            
            if not d.canceled:
                self.game.user[row][col] = d.letter
                event.widget.configure(text=d.letter)
                self.format_entry(row, col)
                
    def clear_value(self, event=None):
        if event and event.widget:
            row = event.widget.row
            col = event.widget.col
            self.game.user[row][col] = ''
            event.widget.configure(text='')
            self.format_entry(row, col)
        
    def insert_right(self, event=None):
        if event and event.widget:
            row = event.widget.row
            col = event.widget.col
            d = BlockEditorDlg(self.root, row, col, self.game.user[row][col], label_text='Enter text to insert right')
            if not d.canceled:
                val = d.val.strip().lower()
                for letter in val:
                    if not letter.isalpha():
                        letter = ''
                    if col < len(self.game.user[row]):
                        self.game.user[row][col] = letter
                        self.format_entry(row, col)
                    col += 1
                    
    def insert_down(self, event=None):
        if event and event.widget:
            row = event.widget.row
            col = event.widget.col
            d = BlockEditorDlg(self.root, row, col, self.game.user[row][col], label_text='Enter text to insert down')
            if not d.canceled:
                val = d.val.strip().lower()
                for letter in val:
                    if not letter.isalpha():
                        letter = ''
                    if row < len(self.game.user):
                        self.game.user[row][col] = letter
                        self.format_entry(row, col)
                    row += 1
    
    def saveGame(self, event=None):
        filename = tkFileDialog.asksaveasfilename()
        if filename:
            self.game.save(filename)
    

    def reset_board_editor(self):
        self.add_bench()
        for row_num in xrange(len(self.board)):
            row = self.board[row_num]
            for col_num in xrange(len(row)):
                self.format_entry(row_num, col_num)

    def load_game(self, event=None):
        game = load_game()
        if (game):
            self.game = game
            self.reset_board_editor()
    
    def clear_board(self, event=None):
        if tkMessageBox.askokcancel("Lose Changes?", 
                                    "Clearing the board will lose any unsaved changes.\n Proceed?"):
            self.game = Game()
            self.reset_board_editor()
    
    def solve(self, event=None):
        process_solve(self.game, self.board)
            
    def format_entry(self,row, col):
        if self.board[row][col] == 'T':
            self.entries[row][col].configure(background='#FD8')
        elif self.board[row][col] == 't':
            self.entries[row][col].configure(background='#8F8')
        elif self.board[row][col] == 'D':
            self.entries[row][col].configure(background='#F88')
        elif self.board[row][col] == 'd':
            self.entries[row][col].configure(background='#88F')
        self.entries[row][col].configure(foreground='#666', text='')
        if self.game.user[row][col] and self.game.user[row][col].isalpha():
            self.entries[row][col].configure(foreground='#F00', text=self.game.user[row][col])
        elif self.board[row][col] == 'T':
            self.entries[row][col].configure(text='TW')
        elif self.board[row][col] == 't':
            self.entries[row][col].configure(text='TL')
        elif self.board[row][col] == 'D':
            self.entries[row][col].configure(text='DW')
        elif self.board[row][col] == 'd':
            self.entries[row][col].configure(text='DL')
        